package com.example.backblog.config;

import com.example.backblog.annotation.UserIdParameter;
import com.example.backblog.util.ConstantUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserIdHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        boolean hasMethodAnnotation = parameter.hasParameterAnnotation(UserIdParameter.class);
        return hasMethodAnnotation;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
//        Object attribute = webRequest.getAttribute(ConstUtil.USER_ID, RequestAttributes.SCOPE_REQUEST);
        HttpServletRequest nativeRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        Object userId = nativeRequest.getSession().getAttribute(ConstantUtil.USER_SESSION);
        return userId;
    }

}
